package pl.edu.agh.portal.application.portlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import pl.edu.agh.portal.application.types.Employee;
import pl.edu.agh.portal.application.types.Message;
import pl.edu.agh.portal.application.utils.PortletsUtils;

public class MessageListPortlet extends ThesisGenericPortlet {

	private static final String NORMAL_VIEW = "/message_list_portlet.jsp";
	
	private PortletRequestDispatcher normalView;
	
	public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
		ArrayList<Message> projectsList = new ArrayList<Message>();
		Employee employee = new Employee("Darek", "test", "test", Calendar.getInstance().getTime());
		projectsList.add(new Message(1, employee, "Message title"));
		
		String mode = request.getParameter("mode");
		
		if (mode != null && mode.equals("1")) {
			
		} else if (mode != null && mode.equals("2")) {
			
		}
		
		//TODO: Communication with WS - get messages list		
		
		request.setAttribute(PortletsUtils.USER_MESSAGES_KEY, projectsList.toArray(new Message[0]));		
		normalView.include(request, response);
	}
	
	@Override
	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
		String value = request.getParameter(PortletsUtils.MESSAGE_MENU_KEY);		
		if (value == null)	value = "";
		if (value.equals(PortletsUtils.BUTTON_CREATE_MESSAGE)) {
			response.sendRedirect("/portal/portal/message_create.psml");
		} else if (value.equals(PortletsUtils.BUTTON_INBOX_MESSAGES)) {
			response.sendRedirect("/portal/portal/message_list.psml?mode=1");
		} else if (value.equals(PortletsUtils.BUTTON_OUTBOX_MESSAGES)) {
			response.sendRedirect("/portal/portal/message_list.psml?mode=2");
		} else {
			response.setPortletMode(PortletMode.VIEW);
		}	
	}	
	
	public void init(PortletConfig config) throws PortletException {
		super.init(config);
		normalView = config.getPortletContext().getRequestDispatcher(NORMAL_VIEW);
	}
	
	public void destroy() {
		normalView = null;
		super.destroy();
	}
	
}
